<template>
  <div>
    <div class="board">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>影厅管理</el-breadcrumb-item>
        <el-breadcrumb-item>影厅信息</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="bill-management-container">
    <div style='padding:10px 0px'>
      <el-row :gutter="24">
        <el-col :span="4" >
          <el-input v-model="pageData.searchText" placeholder="搜索影厅类别" autocomplete="off" />
        </el-col>
        <el-col :span="2">
          <el-button type="success" @click='handerSearch'>查询</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="success" @click='addDialogVisible=true'>新增</el-button>
        </el-col>
      </el-row>
    </div>
    <el-table :data="pageData.records" style="width: 100%" :header-cell-style="{background: '#800000'}">
      <el-table-column label="影厅名称" width="150" header-align="center" align="center">
        <template #default="scope">
          <span>{{ scope.row.hallName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="影厅类别" width="200" header-align="center" align="center">
        <template #default="scope">
          <span>{{ scope.row.hallCategory }}</span>
        </template>
      </el-table-column>

      <el-table-column label="排数" width="150" header-align="center" align="center">
        <template #default="scope">
          <span>{{ scope.row.rowNums }}</span>
        </template>
      </el-table-column>

      <el-table-column label="每排座位数" width="150" header-align="center" align="center">
        <template #default="scope">
          <span>{{ scope.row.seatNumsRow }}</span>
        </template>
      </el-table-column>

      <el-table-column label="总座位数" width="150" header-align="center" align="center">
        <template #default="scope">
          <span>{{ scope.row.seatNums }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作"header-align="center" align="center">
        <template #default="scope">
          <el-button size="small" type="primary" plain @click="handleEdit(scope.$index, scope.row)">
            编辑
          </el-button>
          <el-button size="small" type="danger" plain @click="handleDelete(scope.$index, scope.row)">
            删除
          </el-button>
          <el-button size="small" type="warning" plain @click="handleSeats(scope.$index, scope.row)">
            座位
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="demo-pagination-block">
      <el-pagination
          v-model:current-page="pageData.current"
          v-model:page-size="pageData.size"
          :page-sizes="[10, 20, 30, 40]"
          :size="pageData.size"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 删除确认对话框 -->
    <el-dialog
        v-model="deleteDialogVisible"
        title="删除提示"
        width="500"
        :before-close="handleClose"
    >
      <span>确认要删除这个影厅吗？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDelete">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增影厅" width="600">
      <el-form :model="addObj" label-width="100px">
        <el-form-item label="影厅名称" prop="hallName">
          <el-input v-model="addObj.hallName" autocomplete="off" />
        </el-form-item>

        <el-form-item label="影厅类别" prop="hallCategory">
          <el-select v-model="addObj.hallCategory" placeholder="请选择影厅类别" style="width: 100%">
            <el-option label="N号激光厅" value="N号激光厅"></el-option>
            <el-option label="IMAX巨幕厅" value="IMAX巨幕厅"></el-option>
            <el-option label="VIP情侣厅" value="VIP情侣厅"></el-option>
            <el-option label="N号影厅" value="N号影厅"></el-option>
            <el-option label="6D影厅" value="6D影厅"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="排起始编号" prop="rowStart">
          <el-input v-model="addObj.rowStart" autocomplete="off" placeholder="如1排/A排，默认1排" />
        </el-form-item>

        <el-form-item label="总排数" prop="rowNums">
          <el-input-number v-model="addObj.rowNums" :min="1" style="width: 100%"></el-input-number>
        </el-form-item>

        <el-form-item label="每排座位数" prop="seatNumsRow">
          <el-input-number v-model="addObj.seatNumsRow" :min="1" style="width: 100%"></el-input-number>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handlerAddCancel">取消</el-button>
          <el-button type="primary" @click="handlerAdd">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑影厅" width="600">
      <el-form :model="editObj" label-width="100px">
        <el-form-item label="影厅名称" prop="hallName">
          <el-input v-model="editObj.hallName" autocomplete="off" />
        </el-form-item>

        <el-form-item label="影厅类别" prop="hallCategory">
          <el-select v-model="editObj.hallCategory" placeholder="请选择影厅类别" style="width: 100%">
            <el-option label="N号激光厅" value="N号激光厅"></el-option>
            <el-option label="IMAX巨幕厅" value="IMAX巨幕厅"></el-option>
            <el-option label="VIP情侣厅" value="VIP情侣厅"></el-option>
            <el-option label="N号影厅" value="N号影厅"></el-option>
            <el-option label="6D影厅" value="6D影厅"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="排起始编号" prop="rowStart">
          <el-input v-model="editObj.rowStart" autocomplete="off" placeholder="如1排/A排，默认1排" />
        </el-form-item>

        <el-form-item label="总排数" prop="rowNums">
          <el-input-number v-model="editObj.rowNums" :min="1" style="width: 100%"></el-input-number>
        </el-form-item>

        <el-form-item label="每排座位数" prop="seatNumsRow">
          <el-input-number v-model="editObj.seatNumsRow" :min="1" style="width: 100%"></el-input-number>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handlerEditCancel">取消</el-button>
          <el-button type="primary" @click="handlerEditCommit">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="seatDialogVisible" title="安排座位" :width="calculateDialogWidth()">
      <div>
        <div style="margin-bottom: 15px;">
          <span style="margin-right: 15px;">启用</span>
          <el-checkbox v-model="seatEnableAll" @change="toggleAllSeats">全部启用</el-checkbox>
          <el-checkbox v-model="seatDisableAll" @change="toggleAllSeats">全部禁用</el-checkbox>
        </div>

        <div class="seat-grid">
          <div v-for="row in seatRows" :key="row" class="seat-row">
            <div class="row-label">{{ row }}排</div>
            <div class="seat-columns">
              <el-checkbox
                  v-for="col in seatColumns"
                  :key="col"
                  v-model="seatMap[`${row}-${col}`]"
                  :label="col"
                  class="seat-checkbox"
              ></el-checkbox>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="seatDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveSeatArrangement">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  </div>
</template>

<script setup>
import {ref, onMounted} from "vue"
import api from '../api'
import lodash from 'lodash'
import {ElMessage} from "element-plus";

const pageData = ref({
  records: [],
  total: 0,
  size: 10,
  current: 1,
  pages: 1,
  searchText: ''
});

const handerSearch = () => {
  pageData.value.current = 1;
  getTableList();
}

const deleteDialogVisible = ref(false);
const deleteObj = ref({
  hallId: '',
  index: -1
});

// 组件挂载后执行的钩子函数
onMounted(function () {
  getTableList();
});

const addDialogVisible = ref(false);
const addObj = ref({
  hallName: '',
  hallCategory: '',
  rowStart: '1',
  rowNums: 10,
  seatNumsRow: 10,
  seatNums: 100,
  seatState: '{}',
  delState: 0
});

// 获取表格数据
const getTableList = async () => {
  const page = {
    current: pageData.value.current,
    size: pageData.value.size,
    searchText: pageData.value.searchText
  }
  if(!page.searchText){
    page.searchText = "";
  }
  const result = await api.getHallPage(page);
  pageData.value = result;
  pageData.value.searchText = page.searchText;
}

const handlerAddCancel = () => {
  addObj.value = {
    hallName: '',
    hallCategory: '',
    rowStart: '1',
    rowNums: 10,
    seatNumsRow: 10,
    seatNums: 100,
    seatState: '{}',
    delState: 0
  };
  addDialogVisible.value = false;
}

const handlerAdd = async () => {
  // 计算总座位数
  addObj.value.seatNums = addObj.value.rowNums * addObj.value.seatNumsRow;

  try {
    // 验证seatState是否为合法JSON
    JSON.parse(addObj.value.seatState);
    await api.addHall(addObj.value);
    getTableList();
    addDialogVisible.value = false;
  } catch (e) {
    ElMessage.error('座位状态必须是有效的JSON格式');
  }
}

const editDialogVisible = ref(false);
const editObj = ref({
  hallId: '',
  hallName: '',
  hallCategory: '',
  rowStart: '1',
  rowNums: 10,
  seatNumsRow: 10,
  seatNums: 100,
  seatState: '{}',
  delState: 0
});

const handleEdit = (index, row) => {
  editDialogVisible.value = true;
  editObj.value = lodash.clone(row);
}

const handlerEditCancel = () => {
  editDialogVisible.value = false;
}

const handlerEditCommit = async () => {
  // 计算总座位数
  editObj.value.seatNums = editObj.value.rowNums * editObj.value.seatNumsRow;

  try {
    // 验证seatState是否为合法JSON
    JSON.parse(editObj.value.seatState);
    await api.editHall(editObj.value);
    getTableList();
    editDialogVisible.value = false;
  } catch (e) {
    ElMessage.error('座位状态必须是有效的JSON格式');
  }
}

const handleDelete = (index, row) => {
  deleteObj.value.hallId = row.hallId;
  deleteObj.value.index = index;
  deleteDialogVisible.value = true;
}

const confirmDelete = async () => {
  await api.deleteHall(deleteObj.value.hallId);
  pageData.value.records.splice(deleteObj.value.index, 1);
  getTableList();
  deleteDialogVisible.value = false;
}

// 改变分页行数
const handleSizeChange = (val) => {
  pageData.value.size = val;
  getTableList();
}

// 改变当前页码
const handleCurrentChange = (val) => {
  pageData.value.current = val;
  getTableList();
}

  const seatDialogVisible = ref(false);
  const currentHallId = ref('');
  const seatEnableAll = ref(false);
  const seatDisableAll = ref(false);
  const seatMap = ref({});
  const seatRows = ref([]);
  const seatColumns = ref([]);

// Add this method to handle seat button click
  const handleSeats = async (index, row) => {
    currentHallId.value = row.hallId;

    // Initialize seat rows and columns based on hall configuration
    seatRows.value = [];
    seatColumns.value = [];

    // Generate row labels (1, 2, 3... or A, B, C...)
    const isNumberRow = !isNaN(row.rowStart);
    const startCharCode = isNumberRow ? 49 : row.rowStart.charCodeAt(0);

    for (let i = 0; i < row.rowNums; i++) {
      const rowLabel = isNumberRow
          ? String(Number(row.rowStart) + i)
          : String.fromCharCode(startCharCode + i);
      seatRows.value.push(rowLabel);
    }

    // Generate seat numbers (1, 2, 3...)
    for (let i = 1; i <= row.seatNumsRow; i++) {
      seatColumns.value.push(i);
    }

    // Load existing seat state
    try {
      const seatState = row.seatState ? JSON.parse(row.seatState) : {};
      seatMap.value = {};

      // Initialize all seats as enabled by default
      seatRows.value.forEach(row => {
        seatColumns.value.forEach(col => {
          const seatKey = `${row}-${col}`;
          seatMap.value[seatKey] = !seatState[seatKey]; // Inverted because we're tracking enabled state
        });
      });

      // If there's existing seat state, apply it
      if (Object.keys(seatState).length > 0) {
        for (const [key, value] of Object.entries(seatState)) {
          if (seatMap.value.hasOwnProperty(key)) {
            seatMap.value[key] = !value; // Inverted because we're tracking enabled state
          }
        }
      }
    } catch (e) {
      console.error('Error parsing seat state:', e);
      // Initialize all seats as enabled if there's an error
      seatRows.value.forEach(row => {
        seatColumns.value.forEach(col => {
          seatMap.value[`${row}-${col}`] = true;
        });
      });
    }

    seatDialogVisible.value = true;
  };

  const toggleAllSeats = () => {
    const enable = seatEnableAll.value;
    const disable = seatDisableAll.value;

    if (enable && disable) {
      // If both are checked, uncheck the one that wasn't just clicked
      if (seatEnableAll.value) {
        seatDisableAll.value = false;
      } else {
        seatEnableAll.value = false;
      }
    }

    const newState = seatEnableAll.value;
    for (const key in seatMap.value) {
      seatMap.value[key] = newState;
    }
  };
const calculateDialogWidth = () => {
  const baseWidth = 200; // 基础宽度
  const seatWidth = 40; // 每个座位的宽度
  const maxWidth = 1200; // 最大宽度

  // 计算需要的宽度
  const calculatedWidth = baseWidth + (seatColumns.value.length * seatWidth);

  // 返回不超过最大宽度的值
  return Math.min(calculatedWidth, maxWidth) + 'px';
};

const saveSeatArrangement = async () => {
  // Convert the seat map to disabled seats format
  const disabledSeats = {};
  for (const [key, enabled] of Object.entries(seatMap.value)) {
    if (!enabled) {
      disabledSeats[key] = true;
    }
  }

  // Calculate available seats count
  const totalSeats = seatRows.value.length * seatColumns.value.length;
  const disabledCount = Object.keys(disabledSeats).length;
  const availableSeats = totalSeats - disabledCount;

  try {
    // Prepare data for API
    const updateData = {
      hallId: currentHallId.value,
      seatState: JSON.stringify(disabledSeats),
      seatNums: availableSeats
    };

    // Call API
    await api.updateHallSeats(updateData);

    // Refresh the table and close dialog
    getTableList();
    seatDialogVisible.value = false;
    ElMessage.success('座位安排保存成功');
  } catch (e) {
    console.error('Error saving seat arrangement:', e);
    ElMessage.error('保存座位安排失败: ' + (e.message || '未知错误'));
  }
};
// Rest of the existing code remains the same
</script>

<style scoped>
.seat-grid {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #eee;
  padding: 10px;
}
.bill-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}
.el-table {
  margin-top: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  border-radius: 8px;
  overflow: hidden;
}

.seat-row {
  display: flex;
  margin-bottom: 10px;
  align-items: center;
}

.row-label {
  width: 50px;
  font-weight: bold;
}

.seat-columns {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.seat-checkbox {
  margin: 0;
}
</style>